/** 设置 `element-plus` 主题色 */
const setEpThemeColor = (color) => {
  document.documentElement.style.setProperty("--el-color-primary", color)
  for (let i = 1; i <= 2; i++) {
    setPropertyPrimary("dark", i, color)
  }
  for (let i = 1; i <= 9; i++) {
    setPropertyPrimary("light", i, color)
  }
}

function setPropertyPrimary(mode, i, color) {
  document.documentElement.style.setProperty(`--el-color-primary-${mode}-${i}`, dataTheme.value ? darken(color, i / 10) : lighten(color, i / 10))
}

/** 变浅颜色值 */
const lighten = (color, level) => {
  let rgbc = hexToRgb(color)
  for (let i = 0; i < 3; i++) rgbc[i] = Math.floor((255 - rgbc[i]) * level + rgbc[i])
  return rgbToHex(rgbc[0], rgbc[1], rgbc[2])
}

/** 加深颜色值 */
const darken = (color, level) => {
  let rgbc = hexToRgb(color)
  for (let i = 0; i < 3; i++) rgbc[i] = Math.floor(rgbc[i] * (1 - level))
  return rgbToHex(rgbc[0], rgbc[1], rgbc[2])
}
/** hex转rgb */
const hexToRgb = (str) => {
  let hxs = str.replace("#", "").match(/../g)
  for (let i = 0; i < 3; i++) hxs[i] = parseInt(hxs[i], 16)
  return hxs
}

/** rgb转hex */
const rgbToHex = (a, b, c) => {
  let hexs = [a.toString(16), b.toString(16), c.toString(16)]
  for (let i = 0; i < 3; i++) {
    if (hexs[i].length == 1) hexs[i] = `0${hexs[i]}`
  }
  return `#${hexs.join("")}`
}

let dataTheme = {
  value: false,
}

export default setEpThemeColor
